<template>
  <div class="item-one" ref="itemOne">
    <div class="title">
      <span>二维码管理</span>
      <div>
        <el-button type="primary" @click="eqma = true" v-if="userinfo.rolesId == '1' ||userinfo.rolesId == '2'|| userinfo.rolesId == '8'">生成二维码</el-button>
        <!-- <el-button icon="el-icon-refresh"></el-button> -->
      </div>
    </div>
    <div class="container">
      <div id="code"></div>
      <div class="screeningBox">
        <div class="leftBox">
          <div class="leftitem">
            <div class="block">
              <el-date-picker
                v-model="date"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </div>
          </div>
      
          <div id="qrcode" v-show="false"></div>
          
        </div>
        <div class="rightBox">
           <div class="rightitem">
            <el-autocomplete class="servicelevel" v-if="userinfo.rolesId == '1' || userinfo.rolesId == '8'" v-model.trim="agentname" :fetch-suggestions="querySearch_fws" @select="serviceid_fws" placeholder="请输入服务商名称" :trigger-on-focus="false"></el-autocomplete>
          </div>
          <div class="rightitem">
            <el-button icon="el-icon-search" id="sousou" type="primary" @click="soso">搜索</el-button>
            <el-button icon="el-icon-refresh" type="primary" @click="reset">重置</el-button>
          </div>
        </div>
      </div>
     
      <div class="tableBox">
        <el-table
          ref="multipleTable"
          :data="merchantarr"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          stripe
          :header-cell-style="tableHeaderColor"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column align="center" type="index" label="序号"></el-table-column>
          <el-table-column align="center"  prop="agentName" label="服务商名称"></el-table-column>
          <el-table-column align="center"  prop="total" label="二维码数量"></el-table-column>
          <el-table-column align="center"  prop="exported" label="已绑定数量"></el-table-column>
          <el-table-column align="center"  prop="notExported" label="未绑定数量"></el-table-column>
          <el-table-column align="center"  prop="notExported" label="功能类型">
            <template slot-scope="scope">
                <p>{{ getFuncType(scope.row.funcType) }}</p>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="description" label="用途"></el-table-column>
          <el-table-column align="center"  prop="createTime" label="时间"></el-table-column>
          <el-table-column align="center"  prop="operatorName" label="操作员"></el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="120">
            <template slot-scope="scope">
              <!-- <el-button type="text" size="small">导出二维码</el-button> -->
              <el-dropdown trigger="click" @command="handleCommand(scope.row.id)">
              <span class="el-dropdown-link">
                导出二维码<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="aaa(scope.row.id,1)" class="image-btn">公众号二维码</el-dropdown-item>
                <el-dropdown-item @click.native="aaa(scope.row.id,2)">小程序二维码</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="sizechange"
            :page-sizes="[10,20,30,40,50]"
            :page-size='cur_size'
            layout="total, sizes, prev, pager, next, jumper"
            :total="total1"
          ></el-pagination>
        </div>
      </div>
      <br>
      <br>
       <!-- 生成二维码 -->
      <el-dialog v-dialogDrag title="生成二维码" :visible.sync="eqma" width="30%" :close-on-click-modal = "false">
        <el-form
          :model="erinfo"
          status-icon
          ref="erinfo"
          label-width="110px"
          class="demo-dynamic"
        >
          <el-form-item :required="true" label="服务商" >
           <!-- <el-input type="text" v-model="erinfo.name" autocomplete="off"></el-input> -->
            <el-autocomplete
              class="inline-input"
              @keyup.enter.native="soso"
              v-model.trim="conditions.shopno"
              :trigger-on-focus="false"
              :fetch-suggestions="querySearch"
              placeholder="请输入一级服务商名称"
              @select="handleSelect"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item :required="true" label="数量">
            <el-input type="text" v-model.trim="erinfo.total" placeholder="请输入整数" :maxlength='4' autocomplete="off" @keyup.enter.native="erinfo.total=erinfo.total.replace(/[^\d{1,}\d{1,}|\d{1,}]/g,'')"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="用途">
            <el-input type="text" v-model.trim="erinfo.description" autocomplete="off" @keyup.enter.native="erinfo.description = erinfo.description.replace(/[, ]/g,'')"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="功能类型">
            <!--<el-input type="text" v-model.trim="erinfo.funcType" autocomplete="off" @keyup.enter.native="erinfo.funcType = erinfo.funcType"></el-input>-->
            <el-select class="servicelevel" v-model="erinfo.funcType" placeholder="请选择">
              <el-option keys="0" label="默认台卡" :value="0"></el-option>
              <el-option keys="1" label="校园缴费" :value="1"></el-option>
              <el-option keys="2" label="云喇叭台卡" :value="2"></el-option>
              <el-option keys="3" label="缴费通" :value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="eqma = false">取消</el-button>
          <el-button type="primary" :disabled="isDisable" @click="alter()">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getservice, getQrcodeList, addQrcode, getUserSelect, getExportQrcode, agent } from "@/api/api";
import '../../assets/js/jquery-qrcode';
import html2canvas from 'html2canvas';
import JSZip from 'jszip';
import FileSaver from "file-saver"
import { qrcanvas } from 'qrcanvas';
export default {
  name: "item-one",
  data: function() {
    return {
      loading: false,
      id:'',
      fid:'',
      tableData: [],
      cur_page: 1,
      cur_size: 10,
      total1: 0,
      agentname:'',//服务商模糊
      agent_id:'',
      agenList:[],
      date:[],
      multipleSelection: [],
      visible: false,
      isDisable: false,
      servicearr: [],
      merchantarr: [],
      restaurants: [],
      restaurants1: [],
      combined: 10,
      pageCount: "",
      eqma: false,
      erinfo:{
        total:'',
        description:''
      },
      conditions: {
        servicelevel: "",
        servicename: "",
        merchantsstate: "",
        merchantsno: "",
        stardate: "",
        enddate: "",
        serviceid: "",
        aisle: "",
        shopno: ""
      },
      code:[],
      qrCode:[],
      qrcode_img:''
    };
  },
  created() {
    this.userinfo = JSON.parse(sessionStorage.getItem("userInfo"));

    this.$store.dispatch("getNewNum", 6);
    this.getPermissions()
    this.batchlist();
    this.servicelevel1()
    this.getUserSelect()
  },
  // components: {
  //   QRCode: QRCode
  // },
  methods: {
     //修改thead 背景色
     tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background-color: #F0F0F0;font-weight: 500;'
      }
    },
    // 刷新
    refresh() {
      this.$router.go({
        path: 0,
        query: {
          t: Date.now()
        }
      })
    },
    // 分页导航
    handleCurrentChange(val) {
      this.cur_page = val;
      this.batchlist();
      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    getFuncType(v){
    const list = [{label:'默认台卡',value:0},{label:'校园缴费',value:1} , {label:'云喇叭台卡',value:2} , {label:'缴费通',value:3}]
     const data = list.find(item=>item.value == v)
     if(data){
      return data.label
     }else{
      return 
     }
    
  },
    // 分页数量
    sizechange(val) {
      this.cur_size = val;
      this.batchlist();

      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    //多选框
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //  重置
    reset() {
      this.conditions.servicelevel = "";
      this.conditions.servicename = "";
      this.conditions.merchantsstate = "";
      this.conditions.merchantsno = "";
      this.date = []
      this.conditions.serviceid = "";
      this.wx1code = "";
      this.agentname = ''
      this.agent_id = ''
    },
    handleCommand(v) {
        // this.$message('click on item ' + command);
        // this.iscode = []
        // getExportQrcode({
        // type:1,
        // batchId:v
        // }).then(res => {
        //   // consooe.log(res)
        //   for(var i = 0;i < res.data.length;i++){
        //     // this.iscode.push({code:res.data[i].code})
        //     this.iscode = res.data[i].code
        //   }
        // })
    },
    // 搜索
    soso() {
      if(this.date == null || this.date.length == 0 || this.date == undefined) {
        this.date = []
      }
      this.cur_page = 1
      if (this.conditions.servicelevel == 1) {
        this.batchlist("agent1Id");
      } else if (this.conditions.servicelevel == 2) {
        this.batchlist("agen2Id");
      } else {
        this.batchlist("agent1Id");
      }
    },
    //获取权限
    getPermissions(){
      var aaa = sessionStorage.getItem('userInfo')
      var bbb = JSON.parse(aaa)
      this.id = bbb.id
    },
    // 服务商级别
    servicelevel1() {
      getservice({
        type: 1
      }).then(res => {
        this.servicearr = [];
        for (var i = 0; i < res.data.rows.length; i++) {
          this.servicearr.push({
            value: res.data.rows[i].agentname,
            id: res.data.rows[i].id
          });
          this.restaurants.push({'value':res.data.rows[i].fname,'id':res.data.rows[i].fid})
        }
      });
    },
    // 二维码列表
    batchlist(level) {
      getQrcodeList({
        page: this.cur_page,
        size: this.cur_size,
        startTime: this.date[0],
        endTime: this.date[1],
        // keywords: this.conditions.merchantsno,
        agentId: this.agent_id
      }).then(res => {
        if (res.code == 405) {
          sessionStorage. removeItem("token");
          this.$router.push("/login");
        } else {
          this.merchantarr = res.data;
          this.total1 = res.pageInfo.recordCount
          // this.combined = res.pageInfo.recordCount;
          // this.pageCount = res.pageInfo.pageCount;
        }
      });
    },
    //商户模糊查询
    querySearch(queryString, cb) {
        var restaurants = this.restaurants1;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
        getUserSelect({ //商户模糊查询
          page: 1,
          size: 10,
          roleId: 2,
          keywords: this.conditions.shopno
        }).then(res => {
          if(res.code == 200){
            this.restaurants1 = []
            for(var i=0;i<res.data.length;i++){
              this.restaurants1.push({'value':res.data[i].fname,'id':res.data[i].fid})
            }
            let results = queryString
              ? this.restaurants1.filter(this.createFilter(queryString))
              : this.restaurants1;
            // 调用 callback 返回建议列表的数据
            cb(results);
          }
        })
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    //服务商模糊搜索
    querySearch_fws(queryString,cb){
      let that = this
      agent({
        page: 1,
        size: 20,
        keywords: this.agentname
      }).then(res => {
        if(res.code == 405){
          sessionStorage. removeItem('token')
          that.$router.push('/login');
        }else if(res.code == 200){
          that.agenList = []
          for(var i=0;i<res.data.length;i++){
            that.agenList.push({'value':res.data[i].agentname,'id':res.data[i].id})
          }
          let servicearr = that.agenList;
          let results = queryString
            ? servicearr.filter(that.createFilter(queryString))
            : servicearr;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }else{
          that.$message.error(res.message);
        }
      })
    },
    serviceid_fws(item){
      this.agent_id = item.id
    },
    getUserSelect(){
      
    },
    handleSelect(item) {
      this.fid = item.id
      // this.batchlist(item.id)
    },
    //添加二维码账户
    alter(){
      if(this.conditions.shopno !== ''){
        for(var i = 0; i < this.restaurants1.length; i++){
          if(this.conditions.shopno == this.restaurants1[i].value){
            this.fid  = this.restaurants1[i].id
          }
        }
      }
      this.isDisable = true
      const loading = this.$loading({
        lock: true,
        text: '正在生成二维码',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      addQrcode({
        agentId: this.fid,
        total: this.erinfo.total,
        description: this.erinfo.description,
        operatorId: this.id,
        funcType: this.erinfo.funcType
      }).then(res => {
        if (res.code == 405) {
            sessionStorage. removeItem("token");
            this.$router.push("/login");
          } else {
            if(res.code == 405){
              sessionStorage. removeItem('token')
              this.$router.push('/login');
            }else if(res.code == 200){
              this.eqma = false
              this.isDisable = false
              this.erinfo.total = ''
              this.erinfo.description = ''
              this.erinfo.funcType = ''
              this.restaurants1 = []
              loading.close();
              this.batchlist()
            }else if(res.code == 500){
              this.eqma = false
              this.isDisable = false
              this.erinfo.total = ''
              this.erinfo.description = ''
              this.erinfo.funcType = ''
              this.restaurants1 = []
              loading.close();
              this.$message.error(res.message);
            }
          }
      })
    },
    aaa(v,o) {
      this.$confirm(`是否确定导出二维码？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
      }).then(() => {
          this.code = []
          this.qrCode = []
          const loading = this.$loading({
            lock: true,
            text: '正在下载二维码',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          getExportQrcode({
            type: o,
            batchId: v
          }).then(res => {
            var zip = new JSZip();
            var img = zip.folder("二维码");
            var imgData = null;
            var canvas = null;
            var text = "";
            text += "┌───────────────────────────────────────────────────────────┐\r\n";
            text += "│总数:" + res.data.length + "\r\n";
            text += "└───────────────────────────────────────────────────────────┘\r\n";
            text += "┌───────────────────────────────────────────────────────────┐\r\n";
            text += "│创建时间:" + res.data[0].createTime + "\r\n";
            text += "└───────────────────────────────────────────────────────────┘\r\n";
            text += "┌───────────────────────────────────────────────────────────┐\r\n";
            text += "│二维码编号│二维码地址                             │绑定终端│\r\n";
            text += "└───────────────────────────────────────────────────────────┘\r\n";
            for (var i = 0; i < res.data.length; i++) {
              this.code.push(res.data[i].code)
              this.qrCode.push({id:res.data[i].qrCode})
              var label = "";
              if (o == '1') {
                  label = "Nog：" + this.qrCode[i].id;
              } else {
                  label = "Nox：" + this.qrCode[i].id;
              }
              this.qrcode_img = $('#qrcode').qrcode({
                  render: "canvas", //也可以替换为table
                  size: 400,
                  text: this.code[i],
                  label: label,
                  minVersion: 1,       // version range somewhere in 1 .. 40
                  maxVersion: 40,
                  ecLevel: 'L',        //识别度  'L', 'M', 'Q' or 'H'
                  radius: 0.1,         // 0.0 .. 0.5
                  quiet: 2,            //边距
                  mode: 2,
                  fill: '#000',        //二维码颜色 
                  background: '#ffff',    //背景色  
                  mSize: 0.05,          //图片大小
                  mPosX: 0.5,
                  mPosY: 1,
                  fontname: 'sans',
              })
              text += "│" + this.qrCode[i].id + "│" + this.code[i] + "│\r\n";
              //将生成的二维码转换成图片格式
              canvas = this.qrcode_img.find('canvas').get(0);
              //canvas = div.childNodes[0];

              imgData = canvas.toDataURL("image/png");
              img.file("二维码编号[" + this.qrCode[i].id + "].png", imgData.split(",")[1], { base64: true });
              imgData = null;
              canvas = null;
              $('#qrcode').html("");
              
            }
            zip.file("说明.txt", text);
              if (imgData != null) {
                  img.file("二维码编号[" + this.qrCode[i].id + "].png", imgData.split(",")[1], { base64: true });
              }
            zip.generateAsync({type:"blob"}).then(function(content) {
                  FileSaver.saveAs(content, "二维码打包下载.zip",false);
              });
            loading.close();
            // setTimeout(function () { myJqHelp.closeProgress("ExportQRcode");},1000);
            // var this_qrCode = []
            // this_qrCode = this.qrcode_img
            // var canvas = null;
            // var imgdata = null;
            // var zip = new JSZip();
            // var img = zip.folder("二维码");
            // var imgs = document.getElementById("qrcode").getElementsByTagName("img")
            // var imgs = document.getElementById('canvas')
            // var arr = []
            // var ccc= []
            // var bbb = []
            // arr = Array.prototype.slice.call(imgs)
            // var file_name = '';
            // zip.file("说明.txt", text);
            // setTimeout(function(){
            //   for(var i=0;i<arr.length;i++){
            //     ccc.push(arr[i].src.split(',')[1])
            //     if( o == 1){
            //       img.file("二维码编号[Nog：" + this_qrCode[i].id + "].png",ccc[i],{base64: true});
            //     }
            //     if( o == 2){
            //       img.file("二维码编号[Nox：" + this_qrCode[i].id + "].png",ccc[i],{base64: true});
            //     }
            //   }
            //   zip.generateAsync({type:"blob"}).then(function(content) {
            //       FileSaver.saveAs(content, "二维码打包下载.zip",false);
            //   });
            // },100)
            // document.getElementById("qrcode").innerHTML = "";
            // 
          });
      })
      .catch(() => {
          this.$message({
              type: "info",
              message: "已取消"
          });
      });
    },
  }
};
</script>
<style scoped lang='less'>
.title {
  background-color: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.name {
  width: 25%;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 50%;
  padding: 0 15px;
  box-sizing: border-box;
}
.leftBox > .leftitem {
  margin-bottom: 15px;
}
.rightBox > .rightitem {
  margin-bottom: 15px;
}
.merchants {
  width: 50%;
}
.tableBox {
  margin-top: 20px;
}
.servicename {
  width: 60%;
}
// .servicelevel {
//   width: 20%;
// }
.width20 {
  width: 20%;
}
.red {
  color: #f9607d;
}
.blue {
  color: #01aaef;
}
.stitle {
  padding: 5px 0;
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  i {
    margin-left: 10px;
    margin-right: 5px;
  }
  .swarning {
    color: red;
  }
  .warning {
    color: #f9607d;
  }
}
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.inline-input{
  width: 100%;
}
.servicelevel{
  width: 50%;
}
</style>